<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    :title="getTitle"
    :width="adaptiveWidth"
    @ok="handleSubmit"
    :showFooter="showFooter"
    destroyOnClose
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { defineComponent, ref, computed, unref, useAttrs, nextTick } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './user.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { saveOrUpdateUser, getUserRoles, getUserDepartList, getAllRolesListNoByTenant, getAllRolesList } from './user.api';
  import { useDrawerAdaptiveWidth } from '/@/hooks/jeecg/useAdaptiveWidth';
  import { getTenantId } from "/@/utils/auth";
  import { useRoute } from 'vue-router';
  import { useUserStore } from '/@/store/modules/user';
  import { queryDepartTreeSync } from '/@/api/common/api';
  import { getUserDeparts } from '/@/views/system/depart/depart.api';

  // 声明Emits
  const emit = defineEmits(['success', 'register']);
  const attrs = useAttrs();
  const isUpdate = ref(true);
  const rowId = ref('');
  const departOptions = ref([]);
  const route = useRoute();
  const userStore = useUserStore();
  
  // 检测URL是否有type=1参数
  const hasTypeParam = computed(() => route.query.type === '1');
  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 90,
    schemas: formSchema,
    showActionButtonGroup: false,
  });
  // TODO [VUEN-527] https://www.teambition.com/task/6239beb894b358003fe93626
  const showFooter = ref(true);
  //表单赋值
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields();
    showFooter.value = data?.showFooter ?? true;
    setDrawerProps({ confirmLoading: false, showFooter: showFooter.value });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      //租户信息定义成数组
      if (data.record.relTenantIds && !Array.isArray(data.record.relTenantIds)) {
        data.record.relTenantIds = data.record.relTenantIds.split(',');
      } else {
        //【issues/I56C5I】用户管理中连续点两次编辑租户配置就丢失了
        //data.record.relTenantIds = [];
      }

      //查角色/赋值/try catch 处理，不然编辑有问题
      try {
        const userRoles = await getUserRoles({ userid: data.record.id });
        if (userRoles && userRoles.length > 0) {
          data.record.selectedroles = userRoles;
        }
      } catch (error) {}

      //查所属部门/赋值
      const userDepart = await getUserDepartList({ userId: data.record.id });
      if (userDepart && userDepart.length > 0) {
        // 如果不是 type=1，需要限制为当前用户的部门
        if (!hasTypeParam.value) {
          const currentUserInfo = userStore.getUserInfo;
          if (currentUserInfo && currentUserInfo.orgCode) {
            // 获取当前用户的部门信息
            try {
              const allDepartTree = await queryDepartTreeSync();
              // 递归查找当前用户部门
              const findDepartByOrgCode = (nodes, orgCode) => {
                for (const node of nodes || []) {
                  if (node.orgCode === orgCode) {
                    return { key: node.id, title: node.departName, value: node.id, orgCode: node.orgCode };
                  }
                  if (node.children) {
                    const found = findDepartByOrgCode(node.children, orgCode);
                    if (found) return found;
                  }
                }
                return null;
              };
              const currentUserDepart = findDepartByOrgCode(allDepartTree, currentUserInfo.orgCode);
              if (currentUserDepart) {
                // 限制为当前用户的部门
                data.record.selecteddeparts = currentUserDepart.key;
                departOptions.value = [{ label: currentUserDepart.title, value: currentUserDepart.key }];
              } else {
                // 如果找不到当前用户部门，使用原部门（但会禁用）
                let selectDepartKeys = Array.from(userDepart, ({ key }) => key);
                data.record.selecteddeparts = selectDepartKeys.length > 0 ? selectDepartKeys[0] : '';
                departOptions.value = userDepart.map((item) => ({ label: item.title, value: item.key }));
              }
            } catch (error) {
              console.error('获取当前用户部门失败:', error);
              // 出错时使用原逻辑
              let selectDepartKeys = Array.from(userDepart, ({ key }) => key);
              data.record.selecteddeparts = selectDepartKeys.length > 0 ? selectDepartKeys[0] : '';
              departOptions.value = userDepart.map((item) => ({ label: item.title, value: item.key }));
            }
          } else {
            // 没有当前用户信息时，使用原逻辑但会禁用
            let selectDepartKeys = Array.from(userDepart, ({ key }) => key);
            data.record.selecteddeparts = selectDepartKeys.length > 0 ? selectDepartKeys[0] : '';
            departOptions.value = userDepart.map((item) => ({ label: item.title, value: item.key }));
          }
        } else {
          // type=1 时，显示全部部门
          let selectDepartKeys = Array.from(userDepart, ({ key }) => key);
          data.record.selecteddeparts = selectDepartKeys.length > 0 ? selectDepartKeys[0] : '';
          departOptions.value = userDepart.map((item) => ({ label: item.title, value: item.key }));
        }
      }
    } else {
      // 新增时，如果不是 type=1，需要设置当前用户的部门
      if (!hasTypeParam.value) {
        try {
          // 使用 getUserDeparts 直接获取当前用户的部门列表（更可靠）
          const userDepartsResult = await getUserDeparts();
          console.log('当前用户部门信息:', userDepartsResult);
          
          if (userDepartsResult && userDepartsResult.list && userDepartsResult.list.length > 0) {
            const currentUserInfo = userStore.getUserInfo;
            if (currentUserInfo && currentUserInfo.orgCode) {
              // 从用户部门列表中查找匹配当前用户 orgCode 的部门
              const currentDepart = userDepartsResult.list.find(
                item => item.orgCode === currentUserInfo.orgCode || 
                        item.sysOrgCode === currentUserInfo.orgCode
              );
              
              if (currentDepart) {
                // 初始化 data.record 如果不存在
                if (!data.record) {
                  data.record = {};
                }
                // 设置为字符串格式（JSelectDept 单选模式需要字符串）
                data.record.selecteddeparts = String(currentDepart.id);
                departOptions.value = [{ label: currentDepart.departName, value: currentDepart.id }];
                console.log('新增时设置当前用户部门:', currentDepart);
              } else {
                console.warn('未在当前用户部门列表中找到匹配的部门，orgCode:', currentUserInfo.orgCode);
                console.warn('用户部门列表:', userDepartsResult.list);
              }
            }
          } else {
            console.warn('获取当前用户部门列表为空');
          }
        } catch (error) {
          console.error('获取当前用户部门失败:', error);
        }
      }
      //负责部门/赋值
      if (data.record) {
        data.record.departIds && !Array.isArray(data.record.departIds) && (data.record.departIds = data.record.departIds.split(','));
        //update-begin---author:zyf   Date:20211210  for：避免空值显示异常------------
        //update-begin---author:liusq   Date:20231008  for：[issues/772]避免空值显示异常------------
        data.record.departIds =  (!data.record.departIds || data.record.departIds == '') ? [] : data.record.departIds;
        //update-end-----author:liusq   Date:20231008  for：[issues/772]避免空值显示异常------------
        //update-begin---author:zyf   Date:20211210  for：避免空值显示异常------------
      }
    }
    //处理角色用户列表情况(和角色列表有关系)
    data.selectedroles && (await setFieldsValue({ selectedroles: data.selectedroles }));
    //编辑时隐藏密码/角色列表隐藏角色信息/我的部门时隐藏所属部门
    updateSchema([
      {
        field: 'password',
        // 【QQYUN-8324】
        ifShow: !unref(isUpdate),
      },
      {
        field: 'confirmPassword',
        ifShow: !unref(isUpdate),
      },
      {
        field: 'selectedroles',
        show: !data.isRole,
      },
      {
        field: 'departIds',
        componentProps: { options: departOptions },
      },
      {
        field: 'selecteddeparts',
        show: !data?.departDisabled ?? false,
        componentProps: {
          disabled: !hasTypeParam.value, // 无type=1参数时禁用
          // 无type=1参数时，通过 rootPid 限制只显示当前用户的部门树
          // 但由于 JSelectDept 可能不支持 rootPid，我们通过设置默认值来限制
          ...(hasTypeParam.value ? {} : {
            // 如果需要限制数据源，可以在这里设置相关属性
            // JSelectDept 可能需要其他方式来限制树形数据
          }),
        },
      },
      {
        field: 'selectedroles',
        show: !data?.departDisabled ?? false,
        //update-begin---author:wangshuai ---date:20230424  for：【issues/4844】多租户模式下，新增或编辑用户，选择角色一栏，角色选项没有做租户隔离------------
        //判断是否为多租户模式
        componentProps:{
          api: data.tenantSaas?getAllRolesList:getAllRolesListNoByTenant
        }
        //update-end---author:wangshuai ---date:20230424  for：【issues/4844】多租户模式下，新增或编辑用户，选择角色一栏，角色选项没有做租户隔离------------
      },
      //update-begin---author:wangshuai ---date:20230522  for：【issues/4935】租户用户编辑界面中租户下拉框未过滤，显示当前系统所有的租户------------
      {
        field: 'relTenantIds',
        componentProps:{
          disabled: !!data.tenantSaas,
        },
      },
      //update-end---author:wangshuai ---date:20230522  for：【issues/4935】租户用户编辑界面中租户下拉框未过滤，显示当前系统所有的租户------------
    ]);
    //update-begin---author:wangshuai ---date:20230522  for：【issues/4935】租户用户编辑界面中租户下拉框未过滤，显示当前系统所有的租户------------
    if(!unref(isUpdate) && data.tenantSaas){
      await setFieldsValue({ relTenantIds: getTenantId().toString() })
    }
    //update-end---author:wangshuai ---date:20230522  for：【issues/4935】租户用户编辑界面中租户下拉框未过滤，显示当前系统所有的租户------------
    // 无论新增还是编辑，都可以设置表单值
    if (typeof data.record === 'object') {
      await setFieldsValue({
        ...data.record,
      });
    }
    
    // 新增时，如果没有type=1，需要确保当前用户部门已设置
    if (!unref(isUpdate) && !hasTypeParam.value && data.record?.selecteddeparts) {
      try {
        // 等待多个 nextTick 确保组件完全渲染
        await nextTick();
        await nextTick();
        // 设置为字符串格式（JSelectDept 单选模式需要字符串）
        const departValue = String(data.record.selecteddeparts);
        console.log('准备设置部门值:', departValue);
        await setFieldsValue({
          selecteddeparts: departValue,
        });
        // 同时更新 departOptions，确保负责部门下拉框也正确
        if (departOptions.value && departOptions.value.length > 0) {
          await updateSchema([
            {
              field: 'departIds',
              componentProps: { options: departOptions.value },
            },
          ]);
          // 再次确认设置值
          await nextTick();
          await setFieldsValue({
            selecteddeparts: departValue,
          });
        }
      } catch (error) {
        console.error('设置当前用户部门失败:', error);
      }
    }
    // 隐藏底部时禁用整个表单
    //update-begin-author:taoyan date:2022-5-24 for: VUEN-1117【issue】0523周开源问题
    setProps({ disabled: !showFooter.value });
    //update-end-author:taoyan date:2022-5-24 for: VUEN-1117【issue】0523周开源问题
  });
  //获取标题
  const getTitle = computed(() => {
    // update-begin--author:liaozhiyang---date:20240306---for：【QQYUN-8389】系统用户详情抽屉title更改
    if (!unref(isUpdate)) {
      return '新增用户';
    } else {
      return unref(showFooter) ? '编辑用户' : '用户详情';
    }
    // update-end--author:liaozhiyang---date:20240306---for：【QQYUN-8389】系统用户详情抽屉title更改
  });
  const { adaptiveWidth } = useDrawerAdaptiveWidth();

  //提交事件
  async function handleSubmit() {
    try {
      let values = await validate();
      setDrawerProps({ confirmLoading: true });
      values.userIdentity === 1 && (values.departIds = '');
      let isUpdateVal = unref(isUpdate);
      //提交表单
      await saveOrUpdateUser(values, isUpdateVal);
      //关闭弹窗
      closeDrawer();
      //刷新列表
      emit('success',{isUpdateVal ,values});
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
